﻿using System;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace YJKAxisAndEdit
{
	internal class GridBubbleXdata
	{
		private static Schema CreateSimpleSchema()
		{
			SchemaBuilder schemaBuilder = new SchemaBuilder(GridBubbleXdata.m_Guid);
            schemaBuilder.SetReadAccessLevel((AccessLevel)1);
			schemaBuilder.SetSchemaName(GridBubbleXdata.m_sGridId);
			schemaBuilder.AddSimpleField(GridBubbleXdata.m_sGridId, typeof(ElementId));
			return schemaBuilder.Finish();
		}

		private static bool HasSchema(out Schema schema)
		{
			Schema schema2 = Schema.Lookup(GridBubbleXdata.m_Guid);
			schema = schema2;
			return schema2 != null;
		}

		public static void WriteGridId(Element element, ElementId GridId)
		{
			Schema schema = null;
			if (!GridBubbleXdata.HasSchema(out schema))
			{
				schema = GridBubbleXdata.CreateSimpleSchema();
			}
			if (GridBubbleXdata.m_BubbleEnt == null)
			{
				GridBubbleXdata.m_BubbleEnt = new Entity(schema);
			}
			Field field = schema.GetField(GridBubbleXdata.m_sGridId);
			GridBubbleXdata.m_BubbleEnt.Set<ElementId>(field, GridId);
			element.SetEntity(GridBubbleXdata.m_BubbleEnt);
			GridBubbleXdata.m_BubbleEnt = null;
		}

		public static bool ReadGridId(Element element, ref ElementId GridId)
		{
			Schema schema = null;
			if (GridBubbleXdata.HasSchema(out schema))
			{
				Entity entity = element.GetEntity(schema);
				if (entity.IsValid())
				{
					Field field = schema.GetField(GridBubbleXdata.m_sGridId);
					if (field != null)
					{
						GridId = entity.Get<ElementId>(field);
						return true;
					}
				}
			}
			return false;
		}

		public static bool DeleteGridEntity(Element element)
		{
			Schema schema = null;
			return GridBubbleXdata.HasSchema(out schema) && element.DeleteEntity(schema);
		}

		public static Guid m_Guid = new Guid("BC1EB603-AA12-48EF-A973-ABB31F70033B");

		public static string m_sGridId = "GridId";

		public static Entity m_BubbleEnt = null;
	}
}
